import {StackActions, NavigationActions } from "react-navigation"
import { Dialog } from "./Dialog";
// 导航操作 限制手动不能重复跳转到一个同界面
export class Navigator{
    static _navigationRef = null;
    static setNavigatorRef(navRef){
        console.log("导航引用");
        this._navigationRef = navRef;
        // console.log(this._navigationRef);
    }

    static onNavigationStateChange(prevState, newState, action){
        // console.log("导航状态");     
    }

    static getName(recur){
        if(!this._navigationRef){
            return "";
        }
        let route = this._navigationRef.state.nav;
        while(route.routes && route.index < route.routes.length){
            route = route.routes[route.index];
            if(!recur){
                break;
            }
        }
        return route ? route.routeName : "";
    }

    static reset(routeName, params){
        if(!this._navigationRef){
            return;
        }
        const resetAction = StackActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({ routeName, params}),
            ],
        });
        this._navigationRef.dispatch(resetAction)
    }

    static pushInner(routeName, params){
        const pushAction = StackActions.push({
            routeName,
            params,
        });
        this._navigationRef.dispatch(pushAction);
    }

    static _pushing = false;
    static push(routeName, params){
        if(!this._navigationRef){
            return;
        }
        if(this._pushing){
            Dialog.toast("请勿频繁跳转");
            return;
        }
        this._pushing = true;
        setTimeout(()=>this._pushing=false, 700)
        this.pushInner(routeName, params)
    }

    static pushNow(routeName, params){
        if(!this._navigationRef){
            return;
        }
        this.pushInner(routeName, params)
    }

    static pop(){       
        if(!this._navigationRef){
            return;
        }
        const popAction = StackActions.pop({
            n : 1,
        });
        this._navigationRef.dispatch(popAction);      
    }

    static navigate(nav, page, params){
        if(!nav){
            return;
        }
        nav.navigate(page, params);
    }

    static navigateBack(nav){
        if(!nav){
            return;
        }
        nav.goBack(null);
    }
}